package com.inspirationandgenius.welcome;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DBAdapter {

	DatabaseHelper DBHelper;
	Context		   context;
	SQLiteDatabase db;
	
	public DBAdapter(Context context)
	{
		this.context=context;
		DBHelper = new DatabaseHelper(context);
	}
	
	public class DatabaseHelper extends SQLiteOpenHelper{

		Context		   context;
		public DatabaseHelper(Context context) {
			super(context, "igUsers", null, 1);
			this.context = context;
		}
		@Override
		public void onCreate(SQLiteDatabase db) {

				db.execSQL("Create table igUsers (_id integer primary key autoincrement,"
						+ "name text not null , login text not null, "
						+ "pwd text not null, email text not null, "
						+ "image blob , conect_status integer DEFAULT  '0'"
						+");");
		}
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			if(oldVersion < newVersion)
			{
				db.execSQL("DROP TABLE IF EXISTS igUsers");
				onCreate(db);
			}
		}
		
	}
	
	public DBAdapter open()
	{
		db = DBHelper.getWritableDatabase();
		return this;
	}
	
	public void close()
	{
		db.close();
	}
	
	public void Truncate()
	{
		db.execSQL("DELETE FROM igUsers");
	}
	
	public void DisconnectAll_igUsers()
	{
		db.execSQL("UPDATE igUsers SET conect_status=0");
	}
	
	public long insert_igUsers(String name, String login, String pwd, String email, byte[] image)
	{
		ContentValues values = new ContentValues();
		
		values.put("name", name);
		values.put("login", login);
		values.put("pwd", pwd);
		values.put("email", email);
		values.put("conect_status", 0);
		values.put("image",image);
		return db.insert("igUsers", null, values);
	}
	
	public long update_igUser(String login,String pwd)
	{
		ContentValues val = new ContentValues();
		String stat ="1";
		val.put("conect_status", stat);
		
		return db.update("igUsers", val, "login='"+login+"' and pwd='"+pwd+"'", null);
	}
	
	
	public long logout_igUser(String login,String pwd)
	{
		ContentValues val = new ContentValues();
		String stat ="0";
		val.put("conect_status", stat);
		
		return db.update("igUsers", val, "login='"+login+"' and pwd='"+pwd+"'", null);
	}
	
	
	public Cursor getigUsers(String login, String pwd)
	{
		return db.rawQuery("SELECT _id FROM igUsers WHERE login='"+login+"' and pwd='"+pwd+"'", null);
	}
	
	public Cursor getOnline_igUsers()
	{
		return db.rawQuery("SELECT _id FROM igUsers WHERE conect_status=1", null);	
	}
	
	public Cursor getAlligUsers()
	{
		return db.query("igUsers", new String []{
				"_id",
				"name",
				"login",
				"pwd",
				"email",
				"conect_status",
				"image"}, null, null, null, null, null);
	}
	
	
	
}
